﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using Renren.Common;
using Renren.Helpers;
using Renren.Models;
using Renren.ServiceProviders;

namespace Renren.Services
{
    public static class Service
    {
        private static event EventHandler<StateChangedEventArgs> StateChanged;
        private static object locker = new object();
        private static long requestCount = 0;
        private static int VerifyTokenCount = 0;

        public static event EventHandler VerifyTokenFailed;

        public static ServiceState State
        {
            get
            {
                if (requestCount > 0)
                {
                    return ServiceState.Busy;
                }
                return ServiceState.Idle;
            }
        }

        public static void SendRequest(Dictionary<string, string> parameters, Action<string> parseResult)
        {
            SendRequest(ServiceProviderType.Renren, parameters, parseResult);
        }

        public static void SendRequest(ServiceProviderType type, Dictionary<string, string> parameters, Action<string> parseResult)
        {
            StartRequest();
            if (type == ServiceProviderType.Renren && !RenrenSettings.AccessTokenIsVaild)
            {
                if (VerifyTokenCount <= 1)
                {
                    VerifyTokenCount++;
                    if (VerifyTokenFailed != null)
                    {
                        VerifyTokenFailed(RenrenSettings.AccessToken, new EventArgs());
                    }
                }
                EndRequest();
                return;
            }

            // Create web service request
            var serviceProvider = type.GetServiceProvider();
            var request = WebRequest.Create(new Uri(serviceProvider.GetRequestUri(parameters)));
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.BeginGetResponse(
                ar =>
                {
                    EndRequest();
                    WebResponse response = null;
                    try
                    {
                        response = request.EndGetResponse(ar);
                    }
                    catch (WebException e)
                    {
                        ServiceProvider.NotifyResponseError(e.Status.ToString(), e.Message);

                        return;
                    }
                    Stream streamResult = response.GetResponseStream();
                    var result = (new StreamReader(response.GetResponseStream())).ReadToEnd();
                    if (serviceProvider.CheckResponseResult(result))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(parseResult, result);
                    }
                },
                request);
        }

        public static void WritebackStorage(string propertyName, string result)
        {
            if (RenrenSettings.CacheEnabled)
            {
                var cache = IsolatedStorageSettings.ApplicationSettings;
                if (cache.Contains(propertyName) == false)
                {
                    cache.Add(propertyName, result);
                }
                else
                {
                    cache[propertyName] = result;
                }
            }
        }

        public static void WritebackStorage(ActionType type, string result)
        {
            if (RenrenSettings.CacheEnabled)
            {
                var cache = IsolatedStorageSettings.ApplicationSettings;
                if (cache.Contains(type.ToString()) == false)
                {
                    cache.Add(type.ToString(), result);
                }
                else
                {
                    cache[type.ToString()] = result;
                }
            }
        }

        public static void FetchStorage(string propertyName, Action<string> parser)
        {
            if (RenrenSettings.CacheEnabled)
            {
                var cache = IsolatedStorageSettings.ApplicationSettings;
                if (cache.Contains(propertyName) && cache[propertyName] != null)
                {
                    string xml = cache[propertyName] as string;
                    parser(xml);
                }
            }
        }

        public static List<T> FetchStorage<T>(ActionType type, Func<string, List<T>> parser) where T : Model
        {
            List<T> modelList = null;
            if (RenrenSettings.CacheEnabled)
            {
                var cache = IsolatedStorageSettings.ApplicationSettings;
                if (cache.Contains(type.ToString()) && cache[type.ToString()] != null)
                {
                    string xml = cache[type.ToString()] as string;
                    modelList = parser(xml);
                }
            }
            return modelList;
        }

        private static void NotifyStateChanged(ServiceState state)
        {
            if (StateChanged != null)
            {
                StateChanged(null, new StateChangedEventArgs(state));
            }
        }

        private static void StartRequest()
        {
            lock (locker)
            {
                if (requestCount <= 0)
                {
                    NotifyStateChanged(ServiceState.Busy);
                }
                requestCount++;
            }
        }

        private static void EndRequest()
        {
            lock (locker)
            {
                requestCount--;
                if (requestCount <= 0)
                {
                    NotifyStateChanged(ServiceState.Idle);
                    requestCount = 0;
                }
            }
        }
    }
}
